﻿using System.Drawing;
using System.Linq;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using AForge.Imaging;
using ImageProcessor.Shared;
using ImageProcessor.Shared.ImageExtensions;
using Color = System.Windows.Media.Color;

namespace ImageProcessor.Tim
{
    public class EqualizationVM : ImageProcessorBaseVM
    {
        private ImageSource _resultImage;

        public EqualizationVM(MainViewModel mainVM) : base(mainVM)
        {            
        }

        public ImageSource ResultImage
        {
            get { return _resultImage; }
            private set
            {
                if (_resultImage == value)
                    return;
                _resultImage = value;
                OnPropertyChanged("ResultImage");
            }
        }

        protected override void Execute(object obj)
        {
            Bitmap renderedImage = (MainVM.SourceImage as BitmapSource).BitmapSourceToBitmap();

            uint pixels = (uint)renderedImage.Height * (uint)renderedImage.Width;
            decimal Const = 255 / (decimal)pixels;

            int x, y, R, G, B;

            ImageStatistics statistics = new ImageStatistics(renderedImage);

            //Create histogram arrays for R,G,B channels
            int[] cdfR = statistics.Red.Values.ToArray();
            int[] cdfG = statistics.Green.Values.ToArray();
            int[] cdfB = statistics.Blue.Values.ToArray();

            //Convert arrays to cumulative distribution frequency data
            for (int r = 1; r <= 255; r++)
            {
                cdfR[r] = cdfR[r] + cdfR[r - 1];
                cdfG[r] = cdfG[r] + cdfG[r - 1];
                cdfB[r] = cdfB[r] + cdfB[r - 1];
            }

            for (y = 0; y < renderedImage.Height; y++)
            {
                for (x = 0; x < renderedImage.Width; x++)
                {
                    System.Drawing.Color pixelColor = renderedImage.GetPixel(x, y);

                    R = (int)((decimal)cdfR[pixelColor.R] * Const);
                    G = (int)((decimal)cdfG[pixelColor.G] * Const);
                    B = (int)((decimal)cdfB[pixelColor.B] * Const);

                    var newColor = System.Drawing.Color.FromArgb(R, G, B);
                    renderedImage.SetPixel(x, y, newColor);
                }
            }

            ResultImage = renderedImage.BitmapToBitmapSource();
        }

        protected override bool CanExecute(object obj)
        {
            return MainVM.SourceImage != null;
        }
    }
}